import AssistantMessage from "./AssistantMessage";
import UserMessage from "./UserMessage";
import style from "./Messages.module.css";
import { useEffect, useRef } from "react";

type MessagesProps = {
  messages: (UserMessageInterface | AssistantMessageInterface)[];
};

export default function Messages(props: MessagesProps) {
  const { messages } = props;
  const scrollableRef = useRef<HTMLDivElement>(null);

  function scrollToBottom() {
    if (scrollableRef.current) {
      // scrollableRef.current.scrollTop = scrollableRef.current.scrollHeight;
      scrollableRef.current.scrollTo({
        top: scrollableRef.current.scrollHeight,
        behavior: "smooth",
      });
    }
  }

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  return (
    <div className={style.messages} ref={scrollableRef}>
      {messages.map((message) => {
        if (message.role === "assistant") {
          return <AssistantMessage message={message} key={message.content} />;
        }
        return <UserMessage message={message} key={message.content} />;
      })}
    </div>
  );
}
